package com.ds.springboot.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @program: springboot-1-cache
 * @description:
 * @author: Dawson.Zhang
 * @create: 2020-05-28
 **/
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
                                .antMatchers("/level1/**").hasRole("VIP1")
                                .antMatchers("/level2/**").hasRole("VIP2")
                                .antMatchers("/level3/**").hasRole("VIP3");
        //开启自动配置登录功能
        //http.formLogin();
        //1.login请求会自动跳转到登录页，即使你没有画登录页
        //2.重定向：login?error表示登录失败

        //使用自定义的登录页
        http.formLogin()
                        //使用自定义的登录页面
                        .loginPage("/userlogin")
                        //登录页name属性的参数绑定
                        .usernameParameter("username")
                        .passwordParameter("pwd")
                        //指定登录页登录按钮发送的请求地址，如果不指定，默认就是访问自定义登录页面的url，不过方式是post
                        .loginProcessingUrl("/login");

        //开启自动配置的注销功能
        //注销成功之后默认返回到/login页面
        http.logout().logoutSuccessUrl("/");


        //开启记住我功能
        http.rememberMe().rememberMeParameter("remember");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1","VIP2")
            .and()
            .passwordEncoder(new BCryptPasswordEncoder()).withUser("zhangsan").password(new BCryptPasswordEncoder().encode("12356")).roles("VIP2","VIP3")
            .and()
            .passwordEncoder(new BCryptPasswordEncoder()).withUser("wangwu").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1","VIP3");


    }
}
